@model WorkFlowCore.BusinessDemo.Web.Models.OfficialSealApplicationViewModel
@using WorkFlowCore.BusinessDemo.Web.Entities // Required for WorkTaskStatus enum comparison

@{
    ViewData["Title"] = "公章申请详情";
}

<h2>@ViewData["Title"]</h2>

<div>
    <h4>公章申请信息</h4>
    <hr />
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.ApplicantName)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.ApplicantName)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.ApplicantDepartment)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.ApplicantDepartment)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.ApplicationDate)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.ApplicationDate)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.SealType)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.SealType)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Reason)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Reason)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.UsageStartDate)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.UsageStartDate)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.UsageEndDate)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.UsageEndDate)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Quantity)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Quantity)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.AttachedFilesInfo)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.AttachedFilesInfo)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.WorkTaskId)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.WorkTaskId)
        </dd>
        <dt class="col-sm-2">
            创建时间
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.CreatedTime)
        </dd>
        <dt class="col-sm-2">
            最后更新时间
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.UpdatedTime)
        </dd>
        <dt class="col-sm-2">
            创建人ID
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.CreatorUserId)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.CurrentWorkTaskStatusDisplay)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.CurrentWorkTaskStatusDisplay)
        </dd>
    </dl>
</div>

<div class="mt-4">
    <h4>流程相关小部件</h4>
    <div class="row">
        <div class="col-md-12 mb-3">
            <div class="card-body p-2">
                <div style="height:auto;">
                    <iframe id="proveNodeUserFrame"
                        src="https://localhost:5001/index.html#/components/ProveNodeUser?taskId=@Model.WorkTaskId&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjIiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi6JKZ5qCR56uLIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvZW1haWxhZGRyZXNzIjoiYWRtaW4wMDFAcXEub28iLCJFbXBsb3llZU51bWJlciI6IjAwMiIsImV4cCI6MTc0OTA0NjY3MCwiaXNzIjoiV29ya0Zsb3dDb3JlLkJ1c2luZXNzRGVtbyIsImF1ZCI6IldvcmtGbG93Q29yZS5CdXNpbmVzc0RlbW8uV2ViIn0.N5W1j4hClbI0rFAtwpuyFsEyvaulCUHDEU7k2YgJ4h4"
                        width="100%" frameborder="0" allowfullscreen onload="resizeIframe(this)"></iframe>
                </div>
                <div class="mb-3" style="height:auto;"></div>
                <iframe id="proveCardFrame"
                    src="https://localhost:5001/index.html#/components/ProveCard?taskId=@Model.WorkTaskId&access_token="
                    width="100%" frameborder="0" allowfullscreen onload="resizeIframe(this)"></iframe>
            </div>
        </div>
    </div>
    <div class="col-md-12 mb-3">
        <button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#flowDesignModal" style="margin-right:10px;">
            查看流程图
        </button>
        <a asp-action="WorkflowWidgetIntegrationDoc" class="btn btn-outline-info" target="_blank" style="margin-right:10px;">
            查看小部件集成文档
        </a>
        <a asp-action="PublicLinkDoc" class="btn btn-outline-secondary" target="_blank">
            <i class="bi bi-question-circle"></i> 公开链接功能说明
        </a>
    </div>
</div>
<!-- 流程图弹窗 -->
<div class="modal fade" id="flowDesignModal" tabindex="-1" aria-labelledby="flowDesignModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="flowDesignModalLabel">流程图查看</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
                <iframe id="flowDesignFrame"
                    src="https://localhost:5001/index.html#/components/FlowDesign?taskId=@Model.WorkTaskId&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjIiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi6JKZ5qCR56uLIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvZW1haWxhZGRyZXNzIjoiYWRtaW4wMDFAcXEub28iLCJFbXBsb3llZU51bWJlciI6IjAwMiIsImV4cCI6MTc0OTA0NjY3MCwiaXNzIjoiV29ya0Zsb3dDb3JlLkJ1c2luZXNzRGVtbyIsImF1ZCI6IldvcmtGbG93Q29yZS5CdXNpbmVzc0RlbW8uV2ViIn0.N5W1j4hClbI0rFAtwpuyFsEyvaulCUHDEU7k2YgJ4h4"
                    width="100%" height="500" frameborder="0" allowfullscreen></iframe>
            </div>
        </div>
    </div>
</div>
<div class="alert alert-info mt-2" role="alert" style="font-size:0.95em;">
    页面会自动从 Cookie 获取 JwtToken 并填充到小部件 token 参数，无需手动替换。
</div>
<script>
    // 获取cookie
    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) {
            return parts.pop().split(';').shift();
        }
        return null;
    }
    // 页面加载后自动为iframe补充token
    document.addEventListener('DOMContentLoaded', function () {
        var jwt = getCookie('JwtToken');
        if (!jwt) return;
        var token = jwt.replace('Bearer ', '');
        var frames = [
            { id: 'proveCardFrame', base: 'http://localhost:5173/index.html#/components/ProveCard/BusinessDemo/?taskId=@Model.WorkTaskId&access_token=' },
            { id: 'proveNodeUserFrame', base: 'http://localhost:5173/index.html#/components/ProveNodeUser/BusinessDemo/?taskId=@Model.WorkTaskId&access_token=' },
            { id: 'flowDesignFrame', base: 'http://localhost:5173/index.html#/components/FlowDesign/BusinessDemo/?taskId=@Model.WorkTaskId&access_token=' }
        ];
        frames.forEach(function (f) {
            var frame = document.getElementById(f.id);
            if (frame) {
                frame.src = f.base + token;
            }
        });
    });
    // 使iframe高度自适应其内容，增加延迟处理
    function resizeIframe(iframe) {
        setTimeout(function () {
            try {
                if (iframe && iframe.contentWindow && iframe.contentWindow.document.body) {
                    iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
                }
            } catch (e) {
                // 跨域无法自适应时忽略
            }
        }, 300);
    }

    // 父页面监听message，根据id分别设置对应iframe高度
    window.addEventListener('message', function (event) {
        // 日志输出，便于调试
        // 刷新事件处理
        if (event.data && event.data.type === 'refresh') {
            location.reload();
            return;
        }
        if (event.data && event.data.type === 'resize' && event.data.height) {
            switch (event.data.id) {
                case 'Workflow-ProveCard':
                    {
                        var iframe = document.getElementById('proveCardFrame');
                        if (iframe) {
                            iframe.style.height = event.data.height + 'px';
                        }
                        break;
                    }
                case 'Workflow-ProveNodeUser':
                    {
                        var iframe = document.getElementById('proveNodeUserFrame');
                        if (iframe) {
                            iframe.style.height = event.data.height + 'px';
                        }
                        break;
                    }
                case 'Workflow-FlowDesign':
                    {
                        var iframe = document.getElementById('flowDesignFrame');
                        if (iframe) {
                            iframe.style.height = event.data.height + 'px';
                        }
                        break;
                    }
                default:
                    return; // 不处理其他id
            }

        }
    }, false);
</script>
<div class="mt-3">
    @{
        bool canEdit = string.IsNullOrEmpty(Model.WorkTaskId) || Model.CurrentWorkTaskStatus ==
        WorkTaskStatus.Pending.ToString();
        bool canDelete = string.IsNullOrEmpty(Model.WorkTaskId) || Model.CurrentWorkTaskStatus ==
        WorkTaskStatus.Pending.ToString();
        bool canSubmit = string.IsNullOrEmpty(Model.WorkTaskId) || Model.CurrentWorkTaskStatus ==
        WorkTaskStatus.Canceled.ToString() || Model.CurrentWorkTaskStatus == WorkTaskStatus.Pending.ToString();
    }

    @if (canSubmit)
    {
        <form asp-action="SubmitForApproval" asp-route-id="@Model.Id" method="post"
            style="display:inline-block; margin-right:5px;">
            @Html.AntiForgeryToken()
            <button type="submit" class="btn btn-success"
                onclick="return confirm('确定要提交此申请 (#@Model.Id) 进行审批吗？');">提交审批</button>
        </form>
        
        <form asp-action="SubmitForApprovalWithPublicLink" asp-route-id="@Model.Id" method="post"
            style="display:inline-block; margin-right:5px;">
            @Html.AntiForgeryToken()
            <button type="submit" class="btn btn-primary"
                onclick="return confirm('确定要提交此申请 (#@Model.Id) 进行审批吗？（将使用公开链接）');">提交审批（公开链接）</button>
        </form>
    }
    else if (!string.IsNullOrEmpty(Model.WorkTaskId))
    {
        <button type="button" class="btn btn-secondary" disabled style="margin-right:5px;">
            @(Model.CurrentWorkTaskStatusDisplay ?? "已提交")
        </button>
    }

    @if (canEdit)
    {
        <a asp-action="Edit" asp-route-id="@Model.Id" class="btn btn-primary" style="margin-right:5px;">编辑</a>
    }
    else
    {
        <a asp-action="Edit" asp-route-id="@Model.Id" class="btn btn-primary disabled" style="margin-right:5px;"
            aria-disabled="true" onclick="return false;">编辑</a>
    }

    @if (canDelete)
    {
        <a asp-action="Delete" asp-route-id="@Model.Id" class="btn btn-danger" style="margin-right:5px;">删除</a>
    }
    else
    {
        <a asp-action="Delete" asp-route-id="@Model.Id" class="btn btn-danger disabled" style="margin-right:5px;"
            aria-disabled="true" onclick="return false;">删除</a>
    }

    <a asp-action="PublicDetails" asp-route-id="@Model.Id" class="btn btn-info" target="_blank" style="margin-right:5px;">公开查看</a>
    <a asp-action="Index" class="btn btn-secondary">返回列表</a>
</div>
